import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router,ActivatedRoute} from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toMapPoint: any;
declare var toMapPointArr: any;
declare var timestampToTime: any;
declare var trackLineToTime: any;
declare var echarts: any;
declare var INFOBOX_AT_TOP: any;
@Component({
	selector: 'sa-car-path',
	templateUrl: './car-path.component.html',
	styleUrls: ['./trajectory.css']
})
export class CarPathComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			if(queryParams.type === 'detail'){
				this.queryType = queryParams.type;
				this.deviceId = queryParams.deviceId == undefined? '':queryParams.deviceId;
				this.startTime = queryParams.startTime == undefined? '':queryParams.startTime;
				this.endTime = queryParams.endTime == undefined? '':queryParams.endTime;
				this.carNumber = queryParams.carNumber == undefined? '':queryParams.carNumber;
			}
			var railId=localStorage.getItem('railId');
			if(railId){
				localStorage.removeItem('railId');
				this.railManage.railId=railId;
			}
			if(queryParams.nowPage){
				this.isEnterRaill=true;
				this.railManage.nowPage=queryParams.nowPage;
			}
		});
	};
	queryType:string = '';//标记从友捷条转过来的查看车辆轨迹
	railManage:any={
			railId:undefined,
			nowPage:1
		};//存储由围栏管理跳转进来的数据
	isEnterRaill:boolean=false;
	startTime :string= '';
	endTime :string= '';
	carNumber :string= '';
	deviceId :string= '';
	timePlayer:boolean = false; //轨迹播放器
	mp: any; //百度地图
	myTrackLine: any;
	mapSize: any =16;

	trackCanvasLayer: any; //轨迹图层
	startCanvasLayer: any; //轨迹起始点图层
	moveCanvasLayer: any; //轨迹移动添加点图层
	canvasLayerRunning: any; //轨迹播放时的图层
	broadcastSpeed :number= 80; //初始默认播放速度为80毫秒,监听控制器播放速度
	starType :number= 1; //初始播放类型设为1，点击播放变为-1，点击暂停变为1
	progressLeft: number = 0; //播放点的left值
	lineLongness :number= 500; //读条线总长度
	timer: any; //播放轨迹时的定时器
	playStarTime:number = 0; //轨迹播放器开始时间
	playEndTime: any = 24; //轨迹播放器结束时间
	parameterArr :any= []; //记录绘画轨迹时,后台传过来的数据(过滤转成百度坐标系);
	trajectoryControlData :any= []; //记录补充后台传过来的数据(包括丢失部分的数据)
	lostDataArr :any= []; //存储丢失数据的对象
	filterTime:number = 300; //定义过滤丢失数据的时间长  单位：秒
	lostTimeArr :any= []; //记录丢失数据的数据(时间点,时间长,对应在播放器的长度及位置)  

	//	播放器播放,加速,减速图片地址
	playImg :string= 'assets/img/trackImage/play_2x.png';
	quickenImg :string= 'assets/img/trackImage/quick_2x.png';
	moderateImg :string= 'assets/img/trackImage/slow_2x.png';

	//	表格部分参数
	isTable :boolean= false; //是否展开表格
	tableData :any= []; //table数据
	resultTableData:any=[];
	selected :any= []; //row选择的数据
	loadingIndicator: boolean = true; //loading图标
	totalCount :number= 0; //分页总条数
	curPage :number= 1; //分页当前页
	pageSize :number= 5; //内置的分页每页条数
	searchKey :string= ''; //搜索keyword

	//速度颜色控制条参数
	isBarView :boolean= false; //是否打开模块视图
	leftbarWidth :number= 100; //初始默认左边读条最大速度值
	rightbarWidth:number = 100; //初始默认右边读条最小速度值

	adjustSpeed1 :number= 30; //区分调整后保存与取消时,记录上一次的数据
	adjustSpeed2 :number= 100;

	//围栏标注模块
	isRailView :boolean= false; //是否显示添加围栏视图

	companyList :any= []; //获取的公司信息
	railCompany :string= ''; //围栏所属公司

	deployTypeList :any= [{
		name:'装货点',
		value:1
	},{
		name:'卸货点',
		value:2
	}];
	deployType :string= ''; //选中的类型

	railRangeList :any= ['10','20','30','40','50','60','70','80','90','100', '200', '300', '400', '500', '1000', '2000', '3000', '4000', '5000'];
	railRange :any= '500'; //选中的围栏范围

	railName:string = ''; //围栏名称
	stayTime :any= ''; //围栏停留时长
	isRangeView :boolean= true; //是否显示范围,画多边形的时候不显示
	railColor:string = '#00c1de'; //选中的围栏颜色
	isStation :boolean= false; //设为站点
	isRail :boolean= false; //设为围栏
	railGraphlist:any = []; //所有的围栏图形
	graphical: any = false; //当前的围栏图形
	drawingManager: any; //画多边形构造器
	railType :number= 0; //监听画图的类型
	myIcon1: any;
	myIcon2: any;
	editParam: any=false; //修改的参数
	fristPathArr :any= []; //记录第一次画多边形时候的数组
	graphPoint; //监听状态的坐标
	listenMarker; //监听状态的marker
	isEditing: any = false; //图形是否在编辑状态
	tableHeight : any ;
	
	treeStatus:string='收起';//树形图展开或者收起状态
	btnDownTime:number=0;//截留btn点击展开频率
	selectedCompanyName :string= '';//选中公司名称值

	//行政区域参数
	boundaryRegion:any;//行政边界区域构造器
	areaPly:any;//行政边界区域的覆盖图形
	
	weightUnit:string=' 吨';//树形图展开或者收起状态
//树形图部分start 
	carTreeData=[];//车辆树形图数据
	slectedCarId='';//车辆树形图选中的车辆ID
	notOnlineCar=false;
	findCarCount=0;//车辆树搜出的总数
	findCarIndex=0;//车辆树当前定位
	findString='';//搜索提示
	initWeightline=[];//存储从后台过来时的折线数据,不经过过滤
	rangeClick(){
		$('#tree_selectedRange').stop().slideToggle();
	}
	
	//范围树模糊搜索
	rangeSearch(){
		var value = $('#range').val();
		$("#rangeTree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_rangetree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_rangetree').height() * 0.3});
			}
		})
	}
	
	delRange(){
		this.railRange='';
		$('#company').val("");
		if($('#tree_selectedRange')[0].className.indexOf('tree_open')>0){
			$('#range').focus();
			this.rangeSearch();
		}
	}
	initSelectedRange(){
		var that = this;
		var railRangeList = [10,20,30,40,50,60,70,80,90,100,200,300,400,500,1000,2000,3000,4000,5000];
		var rangeTree=[];
		for(let i=0;i<railRangeList.length;i++){
			let obj={
				icon: false,
				id: railRangeList[i],
				text:railRangeList[i]+'米',
			}
			rangeTree.push(obj);
		}
	 	$('#rangeTree').jstree({
			"core": {
			'data':rangeTree,
			"themes": {
				"responsive": true
			},
			"multiple": false,
			"animation": 200,
			"dblclick_toggle": true,
			"expand_selected_onload": true
		},
		"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.railRange=currentNode.id;
			that.rangeChange(currentNode.id);
			$('#tree_selectedRange').slideUp();
		})
	}
	
	//打开公司树
	companyClick(){
		$('#tree_selectedRange').slideUp();
		$('#tree_box').toggleClass('tree_open');
	}
	//擦除公司所选值
	delText(){
		this.selectedCompanyName = '';
		this.railCompany = '';
		$('#company').val("");
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
			this.companySearch();
		}
	}
	//公司树模糊搜索
	companySearch(){
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3});
			}
		})
	}
	//初始化公司树数据
	initCompanyList(){
		var that = this;
		return new Promise(function (resolve, reject) {
			$('#tree').jstree({
				"core": {
					'data': function(obj, callback) {       
						var jsonstr = "[]";       
						var jsonarray = eval('(' + jsonstr + ')');
						var url = 'company/companytree.html';
						$.ajax({        
							type: "GET",
					        url: config.BaseURL + url,
					        dataType: "json",
							xhrFields: {
								withCredentials: true
							},
					        success: function(result) {
								jsonarray = result;  
								callback.call(this, jsonarray);
								that.companyList = jsonarray;
							}         
						});       
					},
				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
			}).bind("activate_node.jstree", function(e, obj) {
				var currentNode = obj.node; // 获取当前节点   
				that.selectedCompanyName = currentNode.text;
				that.railCompany = currentNode.id;
			})
			resolve();
		}.bind(this))
	}
	
	//选中一辆车
	getCartreeMess(carMess){
		
		this.slectedCarEvent(carMess);
	}
	slectedCarEvent(param){
		this.deviceId=param.deviceId;
		this.carNumber=param.carNumber;
		this.lookTrajectory();
	}
//树形图部分end 

	//跳转到围栏管理
	goRailManage(){
		this.router.navigate(['/data-statistics/rail/rail-manage'],{ queryParams: {nowPage:this.railManage.nowPage}});
		setTimeout(function(){
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display','none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display','block');
		},300)
	}
	//初始化绘图围栏的各项参数
	initRailParam() {
		this.isEditing = false; //不在编辑删除状态中
		this.graphical = false; //当前的围栏图形
		this.graphPoint = false;
		this.selectedCompanyName='';
		this.railName = ''; //围栏名称
		this.stayTime = ''; //围栏停留时长
		this.railCompany = ''; //围栏所属公司
		this.deployType = ''; //选中的类型
		this.railRange = '500'; //选中的围栏范围
		this.isRangeView = true; //是否显示范围,画多边形的时候不显示
		this.railColor = '#A90329'; //选中的围栏颜色
		this.isStation = false; //设为站点
		this.isRail = false; //设为围栏
		this.railType = 0; //监听画图的类型
		this.listenMarker = false;
		this.initDrawingStyle();//初始化多边形绘画构造器
		$('.myColor').removeClass('myColor').text('');
		$('.slectColor li').eq(0).addClass('myColor').text('✓ ');
	}
	//颜色选择
	selectedRailCorlor() {
		let that = this;
		$('.slectColor li').click(function() {
			//选择颜色事件
			$('.myColor').text(' ').removeClass('myColor');
			$(this).addClass('myColor').text('✓ ');

			that.railColor = $(this).attr('style').split(':')[1];
			that.initDrawingStyle();//初始化多边形绘画构造器
			if(that.isEditing) {
				var len = that.railGraphlist.length;
				for(var i = 0; i < len; i++) {
					if(that.editParam.point == that.railGraphlist[i].point) {
						that.mp.removeOverlay(that.railGraphlist[i].graphical);
						that.graphical = that.createGraphical(that.railGraphlist[i], that.railColor);
						that.railGraphlist[i].graphical = that.graphical;
						that.mp.addOverlay(that.graphical);
						if(that.railGraphlist[i].lnglats&&that.railGraphlist[i].lnglats!==''){
							//判断为多边形的时候可以进行编辑
							that.graphical.enableEditing();
						}
						
					}
				}
			} else {
				that.mp.removeOverlay(that.graphical);
				if(that.railType == 1) {

					that.graphical = new BMap.Circle(that.graphPoint, that.railRange, {
						strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //创建圆

				}
				if(that.railType == 2) {

					that.graphical = new BMap.Polygon(that.fristPathArr, {
						strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //创建多边形

				}
				that.mp.addOverlay(that.graphical);
			}
		})
	}
	//编辑或者添加围栏的保存事件
	saveDeploy(isSaveAndCreate) {
		var param = {
			id: '',
			name: '',
			companyId: '',
			companyName:this.selectedCompanyName,
			typeId: '',
			typeName: '',
			markerType: 0,
			radius: '',
			site: false,
			electronicFence: false,
			color: '',
			lnglats: '',
			lng: '',
			lat: '',
			stayTime: '',
		};
		if(!this.isEditing) {
			if(!this.graphical) {
				this.jsonApiService.message('请添加围栏标注区域')
				return;
			}
		} else {
			param.id = this.editParam.id;
		}
		param.name = this.railName;
		param.companyId = this.railCompany
		if(param.name == '') {
			this.jsonApiService.message('名称不能为空');
			return;
		}
		if(param.companyId == '') {
			this.jsonApiService.message('请选择所属公司...');
			return;
		}
		if(!this.deployType) {
			this.jsonApiService.message('请选择类型...');
			return;
		}
		if(!this.stayTime) {
			this.jsonApiService.message('请填写围栏停留时长');
			return;
		}
		param.typeId = this.deployType;
		param.typeName = $('.deployType:selected').text();
		param.markerType = this.railType;
		param.site = this.isStation;
		param.electronicFence = this.isRail;
		param.stayTime = this.stayTime;
		var wgsPoint=toWGS84({lng:this.graphPoint.lng,lat:this.graphPoint.lat});
		param.lng = wgsPoint.lng;
		param.lat = wgsPoint.lat;
		var path =this.graphical.getPath();
		var pointStr = '';
		for(var i = 0; i < path.length; i++) {
			var _point=toWGS84({lng:path[i].lng,lat:path[i].lat});
			pointStr = pointStr + _point.lng + ',' + _point.lat + ';'
		}
		param.lnglats = pointStr;
		if(this.railType == 1) {
			param.lnglats = '';
		}
		if(this.isEditing) {
			//判断是否编辑状态
			if(this.editParam.lnglats == '') {
				param.lnglats = '';
			}
		}
		
		if(param.lnglats=='') {
			if(!this.railRange){
				this.jsonApiService.message('请输入正确的围栏范围...');
				return;
			}
			param.radius = this.railRange+'';
		} else {
			param.radius = '0';
		} 
		param.color = this.railColor;
		this.mp.closeInfoWindow();
		let reqdata = '';
		for(var item in param) {
			reqdata = reqdata + '&' + item + '=' + param[item];
		}

		this.jsonApiService.http("mapmarker/addmarker.html", reqdata).subscribe(result => {
			this.graphical.disableEditing();
			if(!result.success) {
				this.jsonApiService.message(result.message);
				return;
			}
			if(this.isEditing&&param.lnglats == ''){
				this.mp.removeOverlay(this.railGraphlist[this.isEditing - 1].graphical);
				this.clearAllGraph();
				// this.initAllRailGraph();
				this.editParam=false;//清空之前可能存在编辑的数据
			}
			var tipsType;
			var backData = result.data;
			backData.point = this.graphPoint;
			backData.marker = this.listenMarker;
			backData.graphical = this.graphical;
			if(this.isEditing || this.isEditing > 0) {
				tipsType = '编辑成功'
				this.railGraphlist[this.isEditing - 1] = backData;
			} else {
				tipsType = '提交成功'
				this.railGraphlist.push(backData);
			}
			this.jsonApiService.message(tipsType);
			var content = this.createContent(backData);
			this.addClickHandler(content, this.listenMarker, backData);
			this.initRailParam();
			this.closeDeploy();
			if(isSaveAndCreate) {
				if(backData.radius < 1) {
					this.listenerRail(2);
				} else {
					this.listenerRail(1);
				}
			}
		})
	}
	//取消添加围栏
	cencelDeploy() {
		if(!this.isEditing) {
			this.mp.removeOverlay(this.graphical);
			this.mp.removeOverlay(this.listenMarker);
		}
		this.initRailParam();
		this.closeDeploy();
	}
	//关闭添加围栏操作模块
	closeDeploy() {
		this.isRailView = false;
		$('.selectRail').removeClass('selectRail');
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			this.railGraphlist[i].graphical.disableEditing();
		}
	}
	//初始化加载所有围栏覆盖物
	initAllRailGraph() {
//		判断是否由围栏管理编辑进来进行围栏编辑的
		var railId=this.railManage.railId;
		this.jsonApiService.http2('mapmarker/getmarker.html', '').subscribe(result => {
			let len = result.data.length;
			if(len < 1) {
//				this.jsonApiService.message('没有围栏图形数据');
				return;
			}
			for(var i = 0; i < len; i++) {
				var obj = toMapPoint(result.data[i]);
				var point = new BMap.Point(obj.lng, obj.lat);
				var marker = new BMap.Marker(point, {
					icon: this.myIcon2
				});
				if(obj.lnglats == '') {
					marker = new BMap.Marker(point, {
						icon: this.myIcon1
					});
				}
				var myGraph = this.wgsGraphical(obj, false);
				this.mp.addOverlay(marker);
				var infoPoint = point; //因点击保存后要初始化一次，所有存储新的坐标位置
				obj.point = point;
				obj.marker = marker;
				obj.graphical = myGraph;
				this.railGraphlist.push(obj);
				if(railId&&railId===obj.id){
					this.editParam = obj;
				}
				var content = this.createContent(obj);
				this.addClickHandler(content, marker, obj);
				this.mp.addOverlay(myGraph);
			}
			if(this.editParam&&railId){
				this.railManage.railId=undefined;
				this.eidtGraphical();
				this.mp.centerAndZoom(this.editParam.point, this.mapSize); 
			}
		})
	}
	//监听marker点击事件
	addClickHandler(content, marker, obj) {
		let that = this;
		marker.addEventListener("click", function(e) {
			that.editParam = obj;
			var infoWindow = new BMap.InfoWindow(content, {
				width: 200,
			}); 
			that.mp.openInfoWindow(infoWindow, e.point); //开启信息窗口
			$('.BMap_bottom').append('<div class="pointer"></div>');
			$('.eidtRail').on('click', function() {
				that.eidtGraphical();
			});
			$('.delRail').on('click', function() {
				that.delGraphical()
			});
		})
	};
	//创建信息info窗口
	createContent(param) {
		if(param.typeId == '' || !param.typeId) {
			param.typeId = '无';
		}
		if(param.typeId ==='1'){
			param.typeName = '装货点'
		}else if(param.typeId ==='2'){
			param.typeName = '卸货点'
		}

		// this.getCompanyName(param.companyId)
		var content = '<div class="mInfoul"><ul>' +
			'<li>标注名称：' + param.name + '<li>' +
			'<li>所属公司：' +  param.companyEntity.companyName + '<li>' +
			'<li>所属角色：' + param.roleName + '<li>' +
			'<li>类型：' + param.typeName + '<li>' +
			'<li style="color:#3BA4F9"><span style="float:right;cursor:pointer" class="eidtRail">编辑</span><span style="cursor:pointer" class="delRail">删除</span><li>' +
			'</ul></div>';
		return content;
	}

	//通过公司id获取公司名
	getCompanyName(id) {
		var companyName = '';
		var len = this.companyList.length;
		for(var i = 0; i < len; i++) {
			if(this.companyList[i].id == id) {
				companyName = this.companyList[i].text;
			}
		}
		return companyName;
	}
	//删除围栏图形
	delGraphical() {
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
			var point = this.editParam.point;
			var len = this.railGraphlist.length;
			var reqdata = "id=" + this.editParam.id;
			this.jsonApiService.http('mapmarker/deletemarker.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
			})
			for(var i = 0; i < len; i++) {
				if(this.editParam.point == this.railGraphlist[i].point) {
					this.mp.removeOverlay(this.railGraphlist[i].graphical);
					this.mp.removeOverlay(this.railGraphlist[i].marker);
				}
			}
			this.mp.closeInfoWindow();
			this.initRailParam();
		})
	}

	//修改图形
	eidtGraphical() {
		if(!this.isEditing) {
			this.mp.removeOverlay(this.listenMarker);
			this.mp.removeOverlay(this.graphical);
		}
		if(this.graphical) {
			this.graphical.disableEditing();
		}
		this.initRailParam();
		this.mp.closeInfoWindow();
		this.isRailView = true;
		this.railName = this.editParam.name;
		this.stayTime = this.editParam.stayTime;
		this.railCompany = this.editParam.companyId;
		// this.selectedCompanyName = this.getCompanyName(this.editParam.companyId);
		this.selectedCompanyName = this.editParam.companyEntity.companyName; 
		this.deployType = this.editParam.typeId;
		this.railRange = this.editParam.radius;
		this.isStation = this.editParam.site;
		this.isRail = this.editParam.electronicFence;
		this.railColor = this.editParam.color;
		this.railType = this.editParam.markerType;
		let that = this;
		$('.slectColor li').each(function() {
			var color = $(this).attr('style').split(':')[1];
			if(that.editParam.color == color) {
				$('.myColor').text(' ').removeClass('myColor');
				$(this).addClass('myColor').text('✓ ');
			}
		})
		var point = this.editParam.point;
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			if(this.editParam.point == this.railGraphlist[i].point) {
				this.graphical = this.railGraphlist[i].graphical;
				this.listenMarker = this.railGraphlist[i].marker;
				this.graphPoint = this.railGraphlist[i].point;
				this.isEditing = i + 1;
				if(this.railGraphlist[i].lnglats == '') {
					this.isRangeView = true;
				} else {
					this.isRangeView = false;
					this.graphical.enableEditing();
				}
				break;
			}
		}
	}
	
	
	//大地坐标系转成百度坐标系后绘图
	wgsGraphical(obj, color) {
		var myGraph;
		if(color) {
			obj.color = color;
		}
		if(obj.lnglats == ''||obj.lnglats == null) {
			
			var point = new BMap.Point(obj.lng, obj.lat);
			myGraph = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆

		} else {
			
			if(!obj.lnglats){
				return;
			}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					var point=toMapPoint({lng:arr[0], lat:arr[1]});
					poitnArr.push(new BMap.Point(point.lng,point.lat))
				}
			}
			myGraph = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		return myGraph;
	}
	
	//根据图形类型创建图形
	createGraphical(obj, color) {
		var myGraph;
		if(color) {
			obj.color = color;
		}
		if(obj.lnglats == ''||obj.lnglats == null) {
			
			var point = new BMap.Point(obj.lng, obj.lat);
			myGraph = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆

		} else {
			
			if(!obj.lnglats){
				return;
			}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					poitnArr.push(new BMap.Point(arr[0], arr[1]))
				}
			}
			myGraph = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		return myGraph;
	}
	//初始化多边形绘画构造器
	initDrawingStyle() {
		let styleOptions = {
			strokeColor: this.railColor, //边线颜色。
			fillColor: this.railColor, //填充颜色。当参数为空时，圆形将没有填充效果。
			strokeWeight: 3, //边线的宽度，以像素为单位。
			strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
			fillOpacity: 0.3, //填充的透明度，取值范围0 - 1。
			strokeStyle: 'solid' //边线的样式，solid或dashed。
		}
		let that = this;
		let drawingManager = new BMapLib.DrawingManager(that.mp, {
			isOpen: false, //是否开启绘制模式
			enableDrawingTool: false, //是否显示工具栏
			drawingToolOptions: {
				offset: new BMap.Size(5, 5), //偏离值
				scale: 0.8,
				drawingModes: [
					'polygon', //多边形
				]
			},
			polygonOptions: styleOptions, //多边形的样式
		});
		this.drawingManager = drawingManager;
		drawingManager.addEventListener("overlaycomplete", function(e) {//围栏点击回调事件
			that.graphical = e.overlay;
			var path = that.graphical.getPath();
			that.fristPathArr = path;
			var last = path.length - 1;
			that.graphPoint = that.getCenterPoint(path);
			that.listenMarker = new BMap.Marker(that.graphPoint, {
				icon: that.myIcon2
			}); //棋子图标
			that.mp.addOverlay(that.listenMarker);
			drawingManager.close();
			that.isRailView = true;
		});
	}
	//	获取中心点
	getCenterPoint(path) {

		var x = 0.0;
		var y = 0.0;
		for(var i = 0; i < path.length; i++) {
			x = x + parseFloat(path[i].lng);
			y = y + parseFloat(path[i].lat);
		}
		x = x / path.length;
		y = y / path.length;
		return new BMap.Point(x, y);
	}
	listenerRail(type) {
		//监听点击圆形或多边形按钮事件
		this.selectedCompanyName = '';
		if(this.graphical) {
			this.jsonApiService.message('请先保存图形');
			return;
		}
		if(type == 1) {
			this.railType = 1;
			this.isRangeView = true;
			$('.selectRail').removeClass('selectRail');
			$('.rail1').addClass('selectRail');
			this.drawingManager.close();
		}
		if(type == 2) {
			this.railType = 2;
			this.isRangeView = false;
			$('.selectRail').removeClass('selectRail');
			$('.rail2').addClass('selectRail');
			this.drawingManager.open();
			this.drawingManager.setDrawingMode('polygon');
		}
	}
	//清除所有的图形
	clearAllGraph() {
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			this.mp.removeOverlay(this.railGraphlist[i].graphical);
			this.mp.removeOverlay(this.railGraphlist[i].marker);
		}
	}

	//当图形为圆形时范围变更事件
	rangeChange(value) {
		if(!this.graphical) {
			return;
		}
		this.railRange = value;
		if(this.isEditing > 0) {
			if(this.railGraphlist[this.isEditing - 1].lnglats == '') {
				this.mp.removeOverlay(this.railGraphlist[this.isEditing - 1].graphical);
				this.railGraphlist[this.isEditing - 1].radius = parseInt(value);
				this.railGraphlist[this.isEditing - 1].graphical = this.createGraphical(this.railGraphlist[this.isEditing - 1], false);
				this.mp.addOverlay(this.railGraphlist[this.isEditing - 1].graphical);
			}
		}

		if(this.railType == 1) {
			this.mp.removeOverlay(this.graphical);
			this.graphical = new BMap.Circle(this.graphPoint, value, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆
			this.mp.addOverlay(this.graphical);
		}

	}
	//初始化日期
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
							that.startTime = time;
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
							that.endTime = time;
						});
						if(that.queryType === "detail"){
							$("#datetimepicker1").val(that.startTime);
							$("#datetimepicker2").val(that.endTime);
						}else{
							var date = new Date();
							$("#datetimepicker2").val(common.getTimeMmss(date));//当前时间
							date.setDate(date.getDate() - 1);//设置前一天
							$("#datetimepicker1").val(common.getTimeMmss(date));
						}
						resolve();
					});
				}
			);
		})

	}
	
	ngOnInit() {
		this.initDate();
		this.initChart()
		$('#barInput').change(($event) => {//速度初始化事件设置
			let arr = $event.target.value.split(';');
			this.leftbarWidth = parseInt(arr[0]);
			this.rightbarWidth = parseInt(arr[1]);
		})
		let map = new BMap.Map('baiduMap',{enableMapClick:false}); //创建地图实例
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		//初始化一个行政边界区域构造器
		this.boundaryRegion = new BMap.Boundary();
		
		
		
		//获取用户当前所在城市
		var myCity = new BMap.LocalCity();
		myCity.get(function (result){
			let point=result.center;
		  	let city = new BMap.Point(point.lng, point.lat); //创建点坐标
		  	map.centerAndZoom(city, 12); //初始化地图，设置中心点坐标和地图级别
		});
		
		
		
		this.mp = map;
		let that = this;
		map.addEventListener("zoomend", function(){
			that.mapSize = this.getZoom();
			if(that.isEditing){
				return;
			}
//			if(that.mapSize > 10) {
//				that.clearAllGraph();
//				that.initAllRailGraph();
//			} else {
//				that.clearAllGraph();
//			}
		});
		this.mp.addEventListener("click", function(e){
			//地图点击添加圆形
			if(that.graphical) {
				return;
			}
			if(that.railType == 1) {
				var point = new BMap.Point(e.point.lng, e.point.lat);
				that.graphPoint = point;
				that.listenMarker = new BMap.Marker(point, {
					icon: that.myIcon1
				});
				that.graphical = new BMap.Circle(that.graphPoint, that.railRange, {
					strokeColor:'blue',
					fillColor:'red',
					strokeWeight:1,
					strokeOpacity:0.2,
					fillOpacity:0.2
				}); //创建圆
				that.mp.addOverlay(that.listenMarker);
				that.mp.addOverlay(that.graphical);
				that.isRailView = true;
			}
		});
		this.mp.addEventListener('dblclick', function(e) {
			map.closeInfoWindow(); //关闭信息窗口
		});
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			this.initSelectedRange();
			this.initCompanyList().then(()=>{
				// this.initAllRailGraph();
			});//初始化公司树
			var tree_box = document.getElementById('tree_box');
			var company = document.getElementById('company');
			var rangeBox=document.getElementById('range');
			//公司树弹窗显示隐藏交互事件
			document.onclick=function(e:any){
				if(!(e.target === company||e.target === rangeBox||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
			        tree_box.className = tree_box.className.replace("tree_open","");
			        $('#tree_selectedRange').slideUp();
			   	} 
			}
		});
		//导入插件插件js
		this.initDrawingStyle();//初始化多边形绘画构造器
		this.initSearch();//区域搜索
		this.selectedRailCorlor();//颜色选择
		this.myIcon1 = new BMap.Icon("assets/img/deployIcon/icon3.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //圆形的marker图标
		this.myIcon2 = new BMap.Icon("assets/img/deployIcon/icon4.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //多边形的marker图标
		this.initTextInfo(); //初始化一个info框
		if(this.queryType === 'detail'){
			setTimeout(function(){
				that.lookTrajectory();
			},800)
		}
		this.addEventWindowResize();
	}
	addEventWindowResize(){
		$(window).on('resize',function(){
			var wrapWidth = $("#wrap").width();
			var divTreeWidth=$(".divTree").width();
			$('.treeRight').width(wrapWidth - divTreeWidth -12 + 'px');
		})
	}
	draggingEvent(){
		var clickX;
		var warp=$("#wrap");
		var treeElement=$(".divTree");
		var treeRight=$(".treeRight");
		var min = 300;
		var max=0;
		var leftOffset = warp.offset().left;
		$(document).on('mousemove', function(e) {
			var wrapWidth = warp.width();
			max=wrapWidth/2;
			var divTreeWidth=treeElement.width();
			var treeRightWidth=treeRight.width();
			clickX = e.pageX;
			//clickX-leftOffset > min   鼠标往右移动,并且大于最小宽度300
			if(clickX-leftOffset > min) {
				if(clickX -leftOffset < max) {
					treeElement.width(clickX - leftOffset + 'px');
					treeRight.width(wrapWidth - clickX + leftOffset -12 + 'px');
				}
				else{
					treeElement.width( max + 'px');
					treeRight.width(wrapWidth - max -12 + 'px');
				}
			} else {
				treeElement.width(min + 'px');
				treeRight.width(wrapWidth - min-12 + 'px');
			}
		});
		
		$(document).mouseup(function(e) {
			e.cancelBubble = true;
			$(document).unbind('mousemove')
		})
	}
	ngOnDestroy() {
		$(document).unbind('keyup'); //移除键盘回车事件
		$(window).unbind('resize');
  	}
	//初始化创建一个info信息窗口
	initTextInfo(){
		let content = '<div><ul>' +
			'<li>标注名称：<li>' +
			'<li>所属公司：<li>' +
			'<li>类型：<li>' +
			'<li style="color:#3BA4F9"><span style="float:right;" class="eidtRail">初始化</span><span class="delRail">删除</span><li>' +
			'</ul></div>';
		var infoWindow = new BMap.InfoWindow(new BMap.Point(0, 0),{
			width: 200,
			heigth: 300
		}); // 创建信息窗口对象 
	}
	
	//初始化地图视图,擦除覆盖物
	initMap() {
		this.mp.removeOverlay(this.trackCanvasLayer);
		this.mp.removeOverlay(this.moveCanvasLayer);
		this.mp.removeOverlay(this.startCanvasLayer);
		this.mp.removeOverlay(this.canvasLayerRunning);
		this.mp.clearOverlays();
		this.parameterArr = [];
		this.trajectoryControlData = [];
		this.lostTimeArr = [];
		this.lostDataArr = [];
		this.xTimelist=[];
		this.xSpeedlist=[];
		this.starType = 1;
		this.progressLeft = 0;
		this.timePlayer = false;
		this.playImg = 'assets/img/trackImage/play_2x.png';
		clearInterval(this.timer);
		// this.initAllRailGraph();
	}

	//	计算两个经纬度之间的距离
	caculationDistance(point1, point2) {
		var lng1 = point1.lng;
		var lat1 = point1.lat;
		var lat2 = point2.lat;
		var lng2 = point2.lng;
		var earthRadius = 6371393; //地球半径(米)
		var radLat1 = lat1 * Math.PI / 180.0;
		var radLat2 = lat2 * Math.PI / 180.0;
		var a = radLat1 - radLat2;
		var b = (lng1 - lng2) * Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * earthRadius;
		return s;
	}
	//根据速度获取轨迹颜色
	getColorBySpeed(speed) {
		var color = '';
		var type = Number(speed);
		if(type < this.leftbarWidth) {
			color = '#4169e1';
		} else if(type >= this.leftbarWidth && type < this.rightbarWidth) {
			color = '#8BC34A';
		} else {
			color = '#ff4500';
		}
		return color;
	}
	
	//获取车辆对应的重量单位
	getWeightUnit(decevid){
		let reqdata = 'deviceId=' + decevid;
		this.jsonApiService.http2("realtime/getRealTimeDataForBase.html", reqdata).subscribe(result => {
			if(result.data.unit=='2'){
					this.weightUnit=' kg';
				}else{
					this.weightUnit=' 吨';
				}
			
			
		})
	}
	// 行驶里程
	totalDistance:string = ''
	
	//加载覆盖物（鼠标移动轨迹）
	lookTrajectory() {
		$('#pointInfo').hide().html('')
		if(this.deviceId == '' || !this.deviceId) {
			this.jsonApiService.message('请选择需要查询的车辆')
			return;
		}
//		layer.load();
		if(this.queryType !== 'detail'){
			this.startTime = $('#datetimepicker1').val();
			this.endTime = $('#datetimepicker2').val();
			if(!this.startTime || this.startTime == '') {
				return;
			}
			if(!this.endTime || this.endTime == '') {
				return;
			}
		}
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,5);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		this.getWeightUnit(this.deviceId);
		this.initMap();
		var mp = this.mp;
		var getColor = this.getColorBySpeed;
		var that = this;
		//	获取轨迹数据
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
		this.jsonApiService.http("track/localtrack.html", reqdata).subscribe(result => {
			// 清空里程数据
			this.totalDistance = ''
			// layer.closeAll('loading');
			this.initWeightline = result.data;
			var data = toMapPointArr(result.data);
			if(data.length < 5) {
				this.jsonApiService.message(result.message);
				return;
			}
			this.linetoMapData=data;
			this.load(); //加载卸货点表格数据渲染
			this.timePlayer = true;
			let point = new BMap.Point(data[0].lng, data[0].lat); //创建点坐标
			this.mp.centerAndZoom(point, 10); //初始化地图，设置中心点坐标和地图级别
			function testUpdate() {}
			this.canvasLayerRunning = new CanvasLayer({
				map: this.mp,
				update: testUpdate,
				zIndex: 10
			});
			this.moveCanvasLayer= new CanvasLayer({
				map: this.mp,
				update: testUpdate,
				zIndex: 10
			});
			this.startCanvasLayer = new CanvasLayer({
				map: this.mp,
				update: function() {
					var ctx = this.canvas.getContext("2d");
					if(!ctx) {
						return;
					}
					ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
					//绘起点图标
					var satrtImg = new Image();
					satrtImg.src = 'assets/img/trackImage/startMarker.png';
					var starPoint = new BMap.Point(data[0].lng,data[0].lat);
					var startPixel = mp.pointToPixel(starPoint);
					ctx.moveTo(startPixel.x, startPixel.y);
					ctx.drawImage(satrtImg, (startPixel.x - 8), (startPixel.y - 30));
					//绘终点图标
					var ednImg = new Image();
					ednImg.src = 'assets/img/trackImage/endMarker.png';
					var endPoint = new BMap.Point(data[data.length - 1].lng,data[data.length - 1].lat);
					var endPixel = mp.pointToPixel(endPoint);
					ctx.moveTo(endPixel.x, endPixel.y);
					ctx.drawImage(ednImg, (endPixel.x - 8), (endPixel.y - 30));
				},
				zIndex: 3
			});

			mp.addOverlay(this.canvasLayerRunning);
			mp.addOverlay(this.startCanvasLayer);
			var trackCanvasLayer = this.trackCanvasLayer;
			var moveCanvasLayer = this.moveCanvasLayer;
			function update() {
				var nextArray = [];
				var fristTime = data[0].loc_time;
				var lastTime = data[data.length - 1].loc_time;
//				var timeDistance = (lastTime - fristTime) / data.length; //取平均时间差
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

				if(data.length !== 0) {
					var lines = 1;
					var lineObj = {};
					var pixelPart = 0;
					var pixelPartUnit = 40;
					for(var _i2 = 0, len = data.length; _i2 < len - 1; _i2 = _i2 + 1) {
						/**绘画路线star*/
						var bmapPoint = new BMap.Point(data[_i2].lng,data[_i2].lat);
                		var nextBmapPoint = new BMap.Point(data[_i2 + 1].lng,data[_i2 + 1].lat);
						var pixel = mp.pointToPixel(bmapPoint);
						var nextPixel = mp.pointToPixel(nextBmapPoint);
						var _speed = data[_i2].speed; //每条数据的速度
						var trackColor = '#4169e1';
						if(_speed >= that.leftbarWidth && _speed < that.rightbarWidth) {
							trackColor = '#8BC34A';
						}
						if(_speed >= that.rightbarWidth) {
							trackColor = '#ff4500';
						}
						pixelPart = pixelPart + Math.pow(Math.pow(nextPixel.x - pixel.x, 2) + Math.pow(nextPixel.y - pixel.y, 2), 0.5);
						ctx.beginPath();
						ctx.moveTo(pixel.x, pixel.y);
						ctx.lineCap = 'round';
						ctx.lineWidth = 3;
						ctx.strokeStyle = trackColor; //根据速度匹配轨迹颜色
						ctx.lineTo(nextPixel.x, nextPixel.y); //所有第一次画线的坐标点；
						ctx.stroke();
						/**end*/
						/**绘画路线箭头标识star*/
						if(pixelPart <= pixelPartUnit) {
							continue;
						}
						pixelPart = 0;
						ctx.beginPath();
//						if(data[_i2 + 1].loc_time - data[_i2].loc_time <= timeDistance) {
							// 箭头一共需要5个点：起点、终点、中心点、箭头端点1、箭头端点2
							var midPixel = new BMap.Pixel(Number((pixel.x + nextPixel.x) / 2), Number((pixel.y + nextPixel.y) / 2));
							// 起点终点距离
							var distance = Math.pow(Math.pow(nextPixel.x - pixel.x, 2) + Math.pow(nextPixel.y - pixel.y, 2), 0.5);
							// 箭头长度
							var pointerLong = 3 * Math.pow(0.5, 0.5);
							var aPixel: any = {
								x: '',
								y: ''
							};
							var bPixel: any = {
								x: '',
								y: ''
							};
							if(nextPixel.x - pixel.x === 0) {
								if(nextPixel.y - pixel.y > 0) {
									aPixel.x = midPixel.x - pointerLong;
									aPixel.y = midPixel.y - pointerLong;
									bPixel.x = midPixel.x + pointerLong;
									bPixel.y = midPixel.y - pointerLong;
								} else if(nextPixel.y - pixel.y < 0) {
									aPixel.x = midPixel.x - pointerLong;
									aPixel.y = midPixel.y + pointerLong;
									bPixel.x = midPixel.x + pointerLong;
									bPixel.y = midPixel.y + pointerLong;
								} else {
									continue;
								}
							} else {
								var k0 = (-Math.pow(2, 0.5) * distance * pointerLong + 2 * (nextPixel.y - pixel.y) * midPixel.y) / (2 * (nextPixel.x - pixel.x)) + midPixel.x;
								var k1 = -((nextPixel.y - pixel.y) / (nextPixel.x - pixel.x));
								var a = Math.pow(k1, 2) + 1;
								var b = 2 * k1 * (k0 - midPixel.x) - 2 * midPixel.y;
								var c = Math.pow(k0 - midPixel.x, 2) + Math.pow(midPixel.y, 2) - Math.pow(pointerLong, 2);
								aPixel.y = (-b + Math.pow(b * b - 4 * a * c, 0.5)) / (2 * a);
								bPixel.y = (-b - Math.pow(b * b - 4 * a * c, 0.5)) / (2 * a);
								aPixel.x = k1 * aPixel.y + k0;
								bPixel.x = k1 * bPixel.y + k0;
							}
							ctx.moveTo(aPixel.x, aPixel.y);
							ctx.lineWidth = 2;
							ctx.strokeStyle = 'white';
							ctx.lineTo(midPixel.x, midPixel.y);
							ctx.lineTo(bPixel.x, bPixel.y);
							ctx.lineCap = 'round';
							if(data[_i2].loc_time >= fristTime && data[_i2 + 1].loc_time <= lastTime) {
								ctx.stroke();
							}
//						}
					}
				}
			}
			trackCanvasLayer = new CanvasLayer({
				map: this.mp,
				update: update
			});
			mp.addOverlay(trackCanvasLayer);

			function setMovePoint(movePoint) {
				if(!movePoint) {
					return;
				}
				var moveUpdate = function moveUpdate() {
					var ctx = this.canvas.getContext("2d");
					if(!ctx) {
						return;
					}
				var angle=movePoint.course;//偏转的角度
				var len=8;//箭头的长度
				var multiple=0.5;//距离圆边的距离，半径r的倍数
				var mapPoint = new BMap.Point(movePoint.lng, movePoint.lat);
				var pixel = mp.pointToPixel(mapPoint);
				var point={x:pixel.x,y:pixel.y};//圆心点坐标
				ctx.beginPath();
				ctx.beginPath();
				ctx.fillStyle='rgba(35,152,255,0.1)';
				ctx.lineWidth = 1;
				ctx.strokeStyle = '#eee';
				ctx.arc(point.x,point.y,len+16,0,2*Math.PI);
				ctx.stroke();
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle='#5d9aeb';	
				ctx.arc(point.x,point.y,len+2,0,2*Math.PI);
				ctx.fill();
				if(angle){
					var pointA={	
							x:point.x-multiple*len*Math.cos(2*Math.PI/360*(-angle+30)),
							y:point.y+multiple*len*Math.sin(2*Math.PI/360*(-angle+30))
						}
					var pointO={	
						x:point.x+multiple*len*Math.sin(2*Math.PI/360*angle),
						y:point.y-multiple*len*Math.cos(2*Math.PI/360*angle)
					}
					var pointB={	
							x:point.x+multiple*len*Math.cos(2*Math.PI/360*(-angle-30)),
							y:point.y-multiple*len*Math.sin(2*Math.PI/360*(-angle-30) )
					}
					ctx.beginPath();	
					ctx.moveTo(pointA.x,pointA.y);
					ctx.lineCap = 'round';
					ctx.lineWidth = 3;
					ctx.strokeStyle = 'white';
					ctx.lineTo(pointO.x,pointO.y);
					ctx.lineTo(pointB.x,pointB.y);
					ctx.stroke();
				}
				else{
					ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
					ctx.beginPath();
					ctx.strokeStyle = '#c2c2c4';
					ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
					ctx.stroke();
					ctx.beginPath();
					ctx.fillStyle = '#fff';
					ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
					ctx.fill();
					ctx.beginPath();
					ctx.fillStyle = '#1496ff';
					ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
					ctx.fill();
				}
				};
				if(typeof moveCanvasLayer != 'undefined') {
					moveCanvasLayer.options.update = moveUpdate;
					moveCanvasLayer._draw();

					return;
				}
				moveCanvasLayer = new CanvasLayer({
					map: mp,
					update: moveUpdate,
					zIndex: 10
				});
			}

			/**
			 * 清除移动的坐标点（鼠标移动轨迹）
			 */
			function clearMovePoint() {

				var update = function update() {
					var ctx = this.canvas.getContext("2d");
					if(!ctx) {
						return;
					}
					ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

				};
				if(typeof moveCanvasLayer != 'undefined') {
					moveCanvasLayer.options.update = update;
					moveCanvasLayer._draw();
					return;
				}
				moveCanvasLayer = new CanvasLayer({
					map: mp,
					update: update,
					zIndex: 10
				});

			}

			var options = {
				size: 7,
				shape: 3,
				color: 'rgba(0, 0, 0, 0)'
			};
			var pointCollection = new BMap.PointCollection(data, options); // 初始化PointCollection

			mp.addOverlay(pointCollection); // 添加Overlay
			var labelText;
			var that=this;
			pointCollection.addEventListener('mouseover', function(e) {
				mp.removeOverlay(labelText);
				var opts = {
				  	position : new BMap.Point(e.point.lng,e.point.lat),    // 指定文本标注所在的地理位置
				  	offset   : new BMap.Size(20, 0)    //设置文本偏移量
				}
				
				var textContent;
				if(e.point.speed){
					
					textContent='时间:'+e.point.uploadDate+', 重量:'+common.twoDecimal(e.point.weight)+', 速度:'+common.twoDecimal(e.point.speed);
				}
				else{
					textContent='时间:'+e.point.uploadDate+', 重量:'+common.twoDecimal(e.point.weight)+', 速度: ';
				}
				labelText = new BMap.Label(textContent, opts);  // 创建文本标注对象
				labelText.setStyle({
					'padding':'5px 300px 25px 5px',
					'fontSize' : "12px",
					'height' : "20px",
					'lineHeight' : "20px",
					'text-align':'center',
					'border-radius':'4px',
					'color':'#333',
					'border':'1px solid #ccc',
					'fontFamily':"微软雅黑"
		 		});
				mp.addOverlay(labelText);   
				that.lineMoveCarPoint(e.point);
			});
			pointCollection.addEventListener('mouseout', function(e) {
				mp.removeOverlay(labelText);
				clearMovePoint();
			});
			
			pointCollection.addEventListener('click', function(e) {
				e.point.deviceId=that.deviceId;
				e.point.carNumber=that.carNumber;
				var geturl=config.BaseURL;
				common.createInfoBox(mp,e.point,geturl);
			});


			let accDistance = 0
			for(var i = 0; i < data.length - 1; i++) {
				this.xTimelist.push(data[i].uploadDate);
				this.xSpeedlist.push(data[i].speed);
				var timeCha = (data[i + 1].loc_time - data[i].loc_time) / 1000; //单位： 秒
				var Distance = this.caculationDistance(data[i], data[i + 1]);
				accDistance += Distance
				if(timeCha > this.filterTime) {
					if(Distance > 100) {
						var max: number = parseInt(String(timeCha / 5));
						this.trajectoryControlData.push(data[i]);
						for(var z = 0; z < max; z++) {
							this.trajectoryControlData.push({
								lng: 0,
								lat: 0,
								speed: 0,
								loc_time: 0,
								weight: 0
							})
						}
						var order = this.trajectoryControlData.indexOf(data[i]);
						this.lostDataArr.push(order);
					}
				} else {
					this.trajectoryControlData.push(data[i]);
				}
			}
			// 存储总的行驶里程
			this.totalDistance = (accDistance / 1000).toFixed(2)
			
			var endtime = this.trajectoryControlData[this.trajectoryControlData.length - 1].loc_time; //数据结束时间
			var startime = this.trajectoryControlData[0].loc_time; //数据开始时间
			var totolaTime = endtime - startime;
			this.playStarTime = trackLineToTime(startime);
			this.playEndTime = trackLineToTime(endtime);
			var len = this.lostDataArr.length;
			var maxLen = this.trajectoryControlData.length; //补充丢失数据后的长度
			var lostWidth = this.lineLongness / maxLen; //每一个点的宽度
			for(var i = 0; i < len-1; i++) {
				var x = parseInt(this.lostDataArr[i]); //在lostDataArr数组中找出每一个丢失的数据是trajectoryControlData的第几个；
				var z: number = data.indexOf(this.trajectoryControlData[x]); //比对原数据的下标，用来计算数据丢失的时间长
				var lostTime = (data[z + 1].loc_time - data[z].loc_time) / 1000 //单位： 秒
				this.lostTimeArr.push({
					lost_time: lostTime,
					loc_time: data[z].loc_time,
					width: (lostTime / 5) * lostWidth,
					left: x * lostWidth
				});
			}
			this.progressLeft = 0; //播放点默认回到0
			this.resetChartview(reqdata);
		})
	}

	//播放器鼠标进入跟离开更改图片样式
	imgMove(type) {
		if(type == 'star') {
			if(this.starType < 1) {
				return;
			}
			this.playImg = 'assets/img/trackImage/playhover_2x.png';
		} else if(type == 'slow') {
			this.moderateImg = 'assets/img/trackImage/slowhover_2x.png';
		} else if(type == 'quick') {
			this.quickenImg = 'assets/img/trackImage/quickhover_2x.png';
		} else {

		}
	}

	//根据轨迹播放状态更改图片
	imgOut(type) {
		if(type == 'star') {
			if(this.starType < 1) {
				return;
			}
			this.playImg = 'assets/img/trackImage/play_2x.png';
		} else if(type == 'slow') {
			this.moderateImg = 'assets/img/trackImage/slow_2x.png';
		} else if(type == 'quick') {
			this.quickenImg = 'assets/img/trackImage/quick_2x.png';
		} else {

		}
	}
	//轨迹播放定时器
	createTimer(speed) {
		if(this.progressLeft < 0) {
			this.progressLeft = 0;
		}
		this.timer = setInterval(function() {
			this.progressLeft = this.progressLeft + 0.5;
			if(this.progressLeft >= this.lineLongness) {
				clearInterval(this.timer);
				this.playImg = 'assets/img/trackImage/play_2x.png';
				this.starType = 1;
				return;
			}
			var index = parseInt(String(this.progressLeft / this.lineLongness * this.trajectoryControlData.length));
			this.setRunningPoint(this.trajectoryControlData[index], index);
		}.bind(this), speed);
	}
	//	轨迹播放跟暂停事件
	playAndPause() {
		if(this.starType > -1) {
			this.playImg = 'assets/img/trackImage/pause_2x.png';
			this.starType = -1;
			this.createTimer(this.broadcastSpeed);
		} else {
			this.playImg = 'assets/img/trackImage/play_2x.png';
			clearInterval(this.timer);
			this.starType = 1;
		}
	}
	//轨迹播放加速,减速事件
	quickAndSlow(type) {
		if(type) {
			this.broadcastSpeed = this.broadcastSpeed / 1.2;
			if(this.broadcastSpeed <= 20) {
				this.broadcastSpeed = 20;
			}
			if(this.starType < 1) {
				clearInterval(this.timer);
				this.createTimer(this.broadcastSpeed);
			}
		} else {
			this.broadcastSpeed = this.broadcastSpeed * 1.2;
			if(this.broadcastSpeed >= 640) {
				this.broadcastSpeed = 640;
			}
			if(this.starType < 1) {
				clearInterval(this.timer);
				this.createTimer(this.broadcastSpeed);
			}
		}
		
		
		
	}

	/**
	 * 绘图函数 播放，拖动显示绘画坐标点的时候需要调用该函数
	 * @param data 
	 * @param order（数据的对应序号）
	 * 地图绘画路线
	 */
	setRunningPoint(data, order) {
		if(data.lat > 0) {
			var mp = this.mp;
			var that=this;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				
				//显示文字信息部分 start
				ctx.beginPath();	
				
				ctx.rect(pixel.x-90,pixel.y-160,180,128);
				ctx.fillStyle="white";
				ctx.strokeStyle = '#CCC';
				ctx.stroke();
				ctx.fill();
				//信息框下面的小三角形
				ctx.beginPath();	
				ctx.moveTo(pixel.x,pixel.y-20);
				ctx.lineTo(pixel.x+6,pixel.y-32);
				ctx.lineTo(pixel.x-6,pixel.y-32);
				ctx.lineTo(pixel.x,pixel.y-20);
				ctx.fillStyle="1A6DDD";
				ctx.fill();
				
				ctx.beginPath();	
				ctx.rect(pixel.x-90,pixel.y-160,180,24);
				ctx.fillStyle="#1A6DDD";
				ctx.fill();
				ctx.beginPath();
				ctx.font="12px Arial";
				ctx.fillStyle='black';
				ctx.fillText('车牌：'+that.carNumber+'['+that.deviceId+']',pixel.x-78,pixel.y-145);
				ctx.fillText('重量：'+data.weight+that.weightUnit,pixel.x-78,pixel.y-120);
				ctx.fillText('速度：'+data.speed+'KM/H',pixel.x-78,pixel.y-100);
				ctx.fillText('经度：'+data.x,pixel.x-78,pixel.y-80);
				ctx.fillText('纬度：'+data.y,pixel.x-78,pixel.y-60);
				ctx.fillText('时间：'+timestampToTime(data.loc_time),pixel.x-78,pixel.y-40);
				//显示文字信息部分 end
				
				
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};
			if(typeof this.canvasLayerRunning != 'undefined') {
				this.canvasLayerRunning.options.update = update;
				this.canvasLayerRunning._draw();
				$('.slowTime').text(timestampToTime(data.loc_time));
				return;
			}
			this.canvasLayerRunning = new CanvasLayer({
				map: this.mp,
				update: update,
				zIndex: 10
			});
			
			
			
			
		} else {
			var z = 0; //用于取出丢失时长
			for(var p = 0; p < this.lostDataArr.length; p++) {
				if(order >= this.lostDataArr[p]) {
					z = p;
				}
			}
			
			if(this.lostTimeArr[z]){
				var lostTime = this.lostTimeArr[z].lost_time;
				var beforeLost = this.lostTimeArr[z].loc_time;
				$('.slowTime').text(trackLineToTime(beforeLost) + '后数据丢失约：' + lostTimeStr(lostTime));
			}
			
			/**
			 * 原理： 取得数据后通过查询出丢失数据的时间点在数据对象的下标位置，存储到lostDataArr对象里面，然后通过计算丢失时间差存储到lostTime对象并且新增坐标为0的数据组成新的数组对象trajectoryControlData，
			 * 当轨迹播放器播放到没有数据的地方的时候，大约计算出下标位置与lostDataArr判断，取出丢失时长，通过比对trajectoryControlData，与parameterArr比对取出丢失数据的开始时间，
			 * 
			 */
		}
	}
	//播放点点击拖动事件 @param e（事件坐标点）
	dragMove(e) {
		$('.progress').css("cursor", "move");
		clearInterval(this.timer);
		this.starType = 1;
		var x = $('.partial-2').offset().left;
		var width = this.lineLongness;
		var that = this;
		$(document).bind("mousemove", function(ev) {
			var _x = ev.pageX - x;
			if(_x < 0) {
				_x = -2;
			}
			if(_x >= width) {
				_x = width;
			}
			that.progressLeft = _x;
			var index = parseInt(String((_x / width) * that.trajectoryControlData.length));
			if(index < 0) {
				index = 0;
			}
			if(index >= that.trajectoryControlData.length) {
				index = that.trajectoryControlData.length - 1;
			}
			that.setRunningPoint(that.trajectoryControlData[index], index);
			$(document).mouseup(function() {
				$('.progress').css("cursor", "default");
				$(this).unbind("mousemove");
				that.playImg = 'assets/img/trackImage/play_2x.png';
			});
		});
	}
	//打开列表
	openUnloadlist() {
		this.tableHeight = $('#s_map_ngx_table').height();
		if(this.isTable) {
			this.isTable = false;
			$('#baiduMap').height(772);
		} else {
			this.isTable = true;
			$('#baiduMap').height(772-this.tableHeight);
		}
	}
	//	表格部分 star 表格搜索
	table_search(word) {
		this.load();
	}
	//  初始化加载list数据
	load() {
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
		this.jsonApiService.http("stats/transportforlist.html", reqdata).subscribe(result => {
			this.loadingIndicator = false;
			if(result.data.length < 1) {
				return;
			}
			for(let item of result.data){
				item.loadTime = common.secondToDate(item.loadTime);
				item.unloadTime = common.secondToDate(item.unloadTime);
				item.transportTime = common.secondToDate(item.transportTime);
				item.distance = common.twoDecimal(item.distance);
				item.avgWeight = common.twoDecimal(item.avgWeight);
				item.maxSpeed = common.twoDecimal(item.maxSpeed);
				item.loadlng = common.twoDecimal(item.loadlng);
				item.loadlat = common.twoDecimal(item.loadlat);
				item.unloadlng = common.twoDecimal(item.unloadlng);
				item.unloadlat = common.twoDecimal(item.unloadlat);
			}
			this.tableData = result.data;
			this.totalCount=result.data.length;
			this.client_pages(0,this.pageSize);
		})
	}
	client_pages(start,length){
		var len = start + Number(length);
		this.resultTableData = this.tableData.slice(start,len);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.client_pages(e.first,e.rows);
	}
	refresh(){
		this.load();
	}
	//播放器读条样式
	styleMethod(obj) {
		const style = {
			'position': 'absolute',
			'width': obj.width + 'px',
			'left': obj.left + 'px',
			'top': '-2px',
			'background': 'white',
			'height': '4px'
		};
		return style;
	}

	//播放点位置样式
	styleProgress() {
		const style = {
			'left': this.progressLeft + 'px',
		};
		return style;
	}
	/**
	 * 设置速度部分
	 */
	//打开设置速度模块
	openBarView(type) {
		if(type == 'open') {
			this.isBarView = true;
		} else {
			this.isBarView = false;
		}
	}
	//保存设置的速度
	saveColorSpeed() {
		this.adjustSpeed1 = this.leftbarWidth;
		this.adjustSpeed2 = this.rightbarWidth;
		this.openBarView('close');
		this.lookTrajectory();
	}
	//取消速度设置
	cencelColorSpeed() {
		this.leftbarWidth = this.adjustSpeed1;
		this.rightbarWidth = this.adjustSpeed2;
		this.openBarView('close');
	}
	//速度设置左拖拉按钮样式
	leftbarStyle() {
		let style = {
			'width': (this.leftbarWidth) / 1.5 + '%'
		};
		return style;
	}
	//速度设置右拖拉按钮样式
	rightbarStyle() {
		let style = {
			'width': (150 - (this.rightbarWidth)) / 1.5 + '%'
		};
		return style;
	}
	//区域搜索
	initSearch(){
		let mp=this.mp;
		var that=this;
		let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : mp
		});
		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
			let str = "";
			let _value = e.fromitem.value;
			let value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			$("#searchResultPanel").text(str);
			let myValue;
			ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件和点击 
				let _value = e.item.value;
				myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
				$("#searchResultPanel").text("onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue);
				setPlace();
			});
			$('#search').click(function(){
				myValue=$('#suggestId').val();
		    	if(myValue!==''){
		    		setPlace();
		    	}
			});
			let setPlace=function (){
				let myFun=function (){
					let pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
					mp.centerAndZoom(pp, 18);
				}
			let local = new BMap.LocalSearch(mp, { //智能搜索
			  onSearchComplete: myFun
			});
			local.search(myValue);
			
			that.drawBoundary(myValue);
		}
		});
	}
	
	//绘画行政区域边界
	drawBoundary(locations){
    	var that=this;
	    this.boundaryRegion.get(locations, function(rs){       //获取行政区域
	    	that.mp.removeOverlay(that.areaPly);  //清除掉之前的边界区域
	        var count = rs.boundaries.length; //行政区域的点有多少个
	      
	      	if(count<1){
	      		
	        	return;
	        }
	        that.areaPly = new BMap.Polygon(rs.boundaries[0], {
	        	strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //建立多边形覆盖物
	        that.mp.addOverlay(that.areaPly);  //添加覆盖物
	        that.mp.setViewport(that.areaPly.getPath());    //调整视野  

	        
		})
	}
	linetoMapData=[];
	myChart:any;
    echartOption:any;
 	yAxiSignal:any;
 	yAxiWeight:any;
 	yAxiSpeed:any;
    initChart(){ 
    	this.initChartyAxi();
	  		this.initChartConfig();
	    	this.myChart=echarts.init(document.getElementById('myChart'));
	    	this.myChart.setOption(this.echartOption,true);
	        this.myChart.resize();
	        $(window).resize(this.myChart.resize);
    }
    xTimelist=[];
	xSpeedlist=[];
	inStopArr=[];
	outStopArr=[];
	resetChartview(reqdata){
		this.inStopArr=[];
		this.outStopArr=[];
		var stopShadow=[];
		this.getStopmarker(0,this.linetoMapData);//获取计算停车点
		this.mapAddStopMarker();//添加停车点
		for(let i=0;i<this.outStopArr.length;i++){
			let time=common.mmsstoTimestamp(this.outStopArr[i].date)-common.mmsstoTimestamp(this.inStopArr[i].date);
			
			if(time>=this.stopTimeFlag){
				var stopMes={
					name: "停车点",
					value: 'P',
					startTIme:this.inStopArr[i].date,
					endTime:this.outStopArr[i].date,
					timelen:common.secondToDate(time/1000),
					coord:[this.inStopArr[i].index,this.inStopArr[i].value],
					lng:this.inStopArr[i].lng,
					lat:this.inStopArr[i].lat,
				}
				stopShadow.push(stopMes);
			}
			
			
		}
		
		
		for(let i=0;i<this.initWeightline.length-2;i++){
			//获取丢失的数据
			let lostStartime = common.mmsstoTimestamp(this.initWeightline[i].uploadDate);
			let lostEndtime = common.mmsstoTimestamp(this.initWeightline[i + 1].uploadDate);
			let lostEndtime2 = common.mmsstoTimestamp(this.initWeightline[i + 2].uploadDate);
			let lostime = (lostEndtime - lostStartime) / 1000;
			if(lostime > 60*10&&lostEndtime2-lostEndtime!==lostEndtime - lostStartime) {
				var point = {
						value: common.secondToDate(lostime),
						xAxis: i,
						yAxis: this.initWeightline[i].weight,
						lostime:lostime,
					};
				stopShadow.push(point);
				//重量时间段丢失
			}
		}
		
		this.jsonApiService.http2("alertlog/queryDeviceShutDownAlarmList.html", reqdata).subscribe(result => {
		let len = result.data.length;
		let offlineError = [];
		if(len > 0) {
			for(let i = 0; i < len; i++) {
				let sort = 0;
				let item = result.data[i];
				let topos = toMapPoint({
					lng: item.lng,
					lat: item.lat,
				});
				if(topos) {
					item.lng = topos.lng;
					item.lat = topos.lat;
				};
				let tim = common.mmsstoTimestamp(item.offTime);
				for(let _i = sort; _i < this.linetoMapData.length; _i++) {
					let _item = this.linetoMapData[_i];
					let _tim = common.mmsstoTimestamp(_item.uploadDate);
					if(_tim - tim >= 0 && _i > 0) {
						sort = _i;
						let errorItem: any = {
							name: '离线异常',
							value: '离',
							xAxis: _i - 1,
							yAxis: this.linetoMapData[_i - 1].weight,
							lostime: '',
							symbol: 'image://assets/img/trackImage/ofline_jb.png',
							symbolSize: 28,
							symbolOffset: ['0', '-50%'],
						};
						for(let keys in item) {
							errorItem[keys] = item[keys];
						}
						stopShadow.push(errorItem);
						break;
					}
				}
			}
		}
		
		
		let obj = {
			name: '车辆速度',
			type: 'line',
			//			yAxisIndex: 2,
			itemStyle: {
				normal: {
					color: '#5793f3',
					lineStyle: {
						width: 1, //折线宽度
						opacity: 0.5,
					}
				}
			},
			data: this.xSpeedlist,
			areaStyle: {
				color: 'rgba(83, 146, 230,0.5)'
			},
			markPoint: {
				data: stopShadow,
				symbolSize: 30,
				itemStyle: {
					normal: {
						color: '#ff6200',
						label: {
							fontSize: 10
						}
					}
				}
			}
		};

		let speedChartline = [];
		speedChartline.push(obj)
		this.echartOption.xAxis.data = this.xTimelist;
		this.echartOption.series = speedChartline;
		this.myChart.setOption(this.echartOption, true);
		$(window).resize(this.myChart.resize);
		this.myChart.on('mouseover', function (params) {
	        if (params.componentType === 'markPoint') {
	        	if(params.name=="离线异常"){
	        		$('#pointInfo').show().html(params.name)
	        	}else{
	        		if(params.name=="停车点"){
	        			$('#pointInfo').show().html('停车时长:'+params.data.timelen)
	        		}
	        		else{
	        			$('#pointInfo').show().html('无数据:'+params.data.value)
	        		}
	        		
	        	}
	            
	        }else{
	            $('#pointInfo').hide().html('')
	        }
    	});
    	this.myChart.on('click', function(params) {
    		//2019-07-14 00:12:56
			console.log(params, 'paramsparams')
			if (params.componentType === 'markPoint'){
				var pointObj=params.data;
				if(!pointObj || !pointObj.lng || !pointObj.lat || pointObj.lng == '0' || pointObj.lat == '0') {
					this.jsonApiService.message('经纬度异常');
					return;
				}
				if(params.name=="离线异常"){
					this.createAbnormalInfo(pointObj);
				}else {
					this.openStopMarkerMes(pointObj);
				}
	           
	        }
		}.bind(this))	
		})
		
	}
	openStopMarkerMes(sotpMes){
		var that=this;
		common.pointGetAdress(sotpMes).then(function(address){
			sotpMes.address=address;
			var html='<div class="infoBox">'+
				'<a></a>'+
				'<div class="content">'+
					'<ul>'+
						'<li><span class="leftSpan">停车时长：</span><span class="rightSpan"> '+sotpMes.timelen+'</span></li>'+
						'<li><span class="leftSpan">开始时间：</span><span class="rightSpan"> '+sotpMes.startTIme+'</span></li>'+
						'<li><span class="leftSpan">结束时间：</span><span class="rightSpan"> '+sotpMes.endTime+'</span></li>'+
						'<li><span class="leftSpan">停车地址：</span><span class="rightSpan"> '+sotpMes.address+'</span></li>'+
					'</ul>'+
				'</div>'+
			'</div>';
			var opts = {
		  		width : 200,     // 信息窗口宽度
				title : '停车信息', // 信息窗口标题	 
			}
			var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象 
			var point = new BMap.Point(sotpMes.lng,sotpMes.lat);
			that.mp.openInfoWindow(infoWindow,point); //开启信息窗口
			setTimeout(function() {
				$('.BMap_bottom').append('<div class="pointer"></div>');
			}, 100);
					
		})
		
	}
	
	
	abnormalInfo;//地图上的异常警报窗口
	//创建生成异常警报弹窗
	createAbnormalInfo(infoData){
			infoData.onTime=infoData.onTime?infoData.onTime:'无';
			if(this.abnormalInfo){
				this.mp.removeOverlay(this.abnormalInfo);
			}
			let point = new BMap.Point(infoData.lng,infoData.lat);
			infoData.abType=infoData.type=='1'?'主板开关机事件':'主机上下电事件';
			let colseTime=infoData.totalSecond+'秒';
			if(infoData.totalSecond>60){
				colseTime=common.secondToDate(infoData.totalSecond);
			}
			let lostWeightHtml='';
			if(infoData.lostime){
				lostWeightHtml='<li><span class="leftSpan">重量丢失：</span><span class="rightSpan"> 约'+common.secondToDate(infoData.lostime)+'</span></li>';
			}
			let html='<div class="abInfobox infoBox">'+
				'<div class="title">'+infoData.carNumber+'异常信息</div>'+
				'<div class="content">'+
					'<ul>'+
//						'<li><span class="leftSpan">所属公司：</span><span class="rightSpan"> '+infoData.companyName+'</span></li>'+
						'<li><span class="leftSpan">消息类型：</span><span class="rightSpan"> 离线警报 </span></li>'+
						'<li><span class="leftSpan">关机时间：</span><span class="rightSpan"> '+infoData.offTime+'</span></li>'+
						'<li><span class="leftSpan">开机时间：</span><span class="rightSpan"> '+infoData.onTime+'</span></li>'+
						'<li><span class="leftSpan">关机时长：</span><span class="rightSpan"> '+colseTime+'</span></li>'+
//						lostWeightHtml+
						'<li><span class="leftSpan">离线地址：</span><span class="rightSpan"> '+infoData.address+'</span></li>'+
					'</ul>'+
				'</div>'+
				'<div class="abpointer"></div>'+
			'</div>';
			this.abnormalInfo = new BMapLib.InfoBox(this.mp,html,{
				boxStyle : {
					width : "240px",
					height : "0"
				},
				offset : new BMap.Size(240, 160),
				closeIconMargin: "12px 0px 0;z-index: 1;width: 18px",
				closeIconUrl :  "assets/img/trackImage/close1.png",
				enableAutoPan : true,
				align : INFOBOX_AT_TOP
			});
			let marker = new BMap.Marker(point);
			this.abnormalInfo.open(marker);
	}
	stopTimeFlag=10*60*1000; //默认判断停车时长10分钟
	stoplistArr=[];
	mapAddStopMarker(){
		for(let item of this.stoplistArr){
			this.mp.removeOverlay(item);	
		}
		this.stoplistArr=[];
		let myIcon = new BMap.Icon('assets/img/trackImage/stop.png', new BMap.Size(20, 30));
		for(let i=0;i<this.inStopArr.length;i++){
			let time=common.mmsstoTimestamp(this.outStopArr[i].date)-common.mmsstoTimestamp(this.inStopArr[i].date);
			
			if(time>=this.stopTimeFlag){
				let stopPoint = new BMap.Point(this.inStopArr[i].lng, this.inStopArr[i].lat);
				
				var marker = new BMap.Marker(stopPoint,{icon: myIcon,offset:new BMap.Size(0,-10)});
				marker.setZIndex(99999)
				this.mp.addOverlay(marker);
				this.stoplistArr.push(marker);
				
				let sotpMes={
					startTIme:this.inStopArr[i].date,
					endTime:this.outStopArr[i].date,
					timelen:common.secondToDate(time/1000),
					address:'',
					lng:this.inStopArr[i].lng,
					lat:this.inStopArr[i].lat,
					
				}
				this.stopClickHandler(sotpMes,marker);
			}
		
			
			
		}
		
		
	}
	//监听标注点击事件
	stopClickHandler (sotpMes,marker) {
		let that=this;
		marker.addEventListener("click",function(e){
			that.openStopMarkerMes(sotpMes);
//			common.pointGetAdress(sotpMes).then(function(address){
//				sotpMes.address=address;
//				var html='<div class="infoBox">'+
//					'<a></a>'+
//					'<div class="content">'+
//						'<ul>'+
//							'<li><span class="leftSpan">停车时长：</span><span class="rightSpan"> '+sotpMes.timelen+'</span></li>'+
//							'<li><span class="leftSpan">开始时间：</span><span class="rightSpan"> '+sotpMes.startTIme+'</span></li>'+
//							'<li><span class="leftSpan">结束时间：</span><span class="rightSpan"> '+sotpMes.endTime+'</span></li>'+
//							'<li><span class="leftSpan">停车地址：</span><span class="rightSpan"> '+sotpMes.address+'</span></li>'+
//						'</ul>'+
//					'</div>'+
//				'</div>';
//				var opts = {
//			  		width : 200,     // 信息窗口宽度
//					title : '停车信息', // 信息窗口标题	 
//				}
//				var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象 
//				var point = new BMap.Point(sotpMes.lng,sotpMes.lat);
//				that.mp.openInfoWindow(infoWindow,point); //开启信息窗口
//				setTimeout(function() {
//					$('.BMap_bottom').append('<div class="pointer"></div>');
//				}, 100);
//	   					
//			})
			
		});
		
		
	}
	getStopmarker(order,trackData) {
		var scarSpeed=2;
		var len = trackData.length;
		var isOut = false;
		for(var i = order; i < len; i++) {
			var speed = +trackData[i].speed;
			if(speed<scarSpeed) { 
				this.inStopArr.push({
					index:i,
					date:trackData[i].uploadDate,
					value:+trackData[i].speed,
					lng:trackData[i].lng,
					lat:trackData[i].lat,
				});
				for(var j = i; j < len-5; j++) {
					var _speed = trackData[j].speed;
					if(_speed>scarSpeed) {
						let timeFlag=false;
						let spped2=trackData[j+1].speed;
						let spped3=trackData[j+2].speed;
						let spped4=trackData[j+3].speed;
						let spped5=trackData[j+4].speed;
						if(spped2>scarSpeed&&spped3>scarSpeed&&spped4>scarSpeed&&spped5>scarSpeed){
							timeFlag=true;
						}
						if(timeFlag){
							isOut = true;
							this.outStopArr.push({
									index:j,
									date:trackData[j].uploadDate,
									value:+trackData[j].speed,
									lng:trackData[j].lng,
									lat:trackData[j].lat,
								});
								
							if(j < len) {
								this.getStopmarker(j,trackData);
							}
							break;
						}
						
					}
					
				}
				if(!isOut) {
					this.outStopArr.push({
						index:len - 1,
						date:trackData[len - 1].uploadDate,
						value:+trackData[len - 1].speed,
						lng:trackData[len-1].lng,
						lat:trackData[len-1].lat,
					});
				}
				break;
			}
		}
	}
	
		//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		if(data.lat > 0) {
			var mp = this.mp;
			var update = function update() {
				
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var angle=data.course;//偏转的角度
				var len=8;//箭头的长度
				var multiple=0.5;//距离圆边的距离，半径r的倍数
				var mapPoint = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(mapPoint);
				var point={x:pixel.x,y:pixel.y};//圆心点坐标
				ctx.beginPath();
				ctx.beginPath();
				ctx.fillStyle='rgba(35,152,255,0.1)';
				ctx.lineWidth = 1;
				ctx.strokeStyle = '#eee';
				ctx.arc(point.x,point.y,len+16,0,2*Math.PI);
				ctx.stroke();
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle='#5d9aeb';	
				ctx.arc(point.x,point.y,len+2,0,2*Math.PI);
				ctx.fill();
				if(angle){
					var pointA={	
							x:point.x-multiple*len*Math.cos(2*Math.PI/360*(-angle+30)),
							y:point.y+multiple*len*Math.sin(2*Math.PI/360*(-angle+30))
						}
					var pointO={	
						x:point.x+multiple*len*Math.sin(2*Math.PI/360*angle),
						y:point.y-multiple*len*Math.cos(2*Math.PI/360*angle)
					}
					var pointB={	
							x:point.x+multiple*len*Math.cos(2*Math.PI/360*(-angle-30)),
							y:point.y-multiple*len*Math.sin(2*Math.PI/360*(-angle-30) )
					}
					ctx.beginPath();	
					ctx.moveTo(pointA.x,pointA.y);
					ctx.lineCap = 'round';
					ctx.lineWidth = 3;
					ctx.strokeStyle = 'white';
					ctx.lineTo(pointO.x,pointO.y);
					ctx.lineTo(pointB.x,pointB.y);
					ctx.stroke();
				}
				else{
					ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
					ctx.beginPath();
					ctx.strokeStyle = '#c2c2c4';
					ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
					ctx.stroke();
					ctx.beginPath();
					ctx.fillStyle = '#fff';
					ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
					ctx.fill();
					ctx.beginPath();
					ctx.fillStyle = '#1496ff';
					ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
					ctx.fill();
				}
				
			};
			if(typeof this.moveCanvasLayer != 'undefined') {
				this.moveCanvasLayer.options.update = update;
				this.moveCanvasLayer._draw();
				return;
			}
			this.moveCanvasLayer = new CanvasLayer({
				map: this.mp,
				update: update,
				zIndex: 10
			});
		}
	}
 	initChartConfig(){
		this.echartOption={
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross' //十字星	
				},
				formatter: function (params) {
					var paramIndex=params[0].dataIndex;
					var pointObj=this.linetoMapData[paramIndex];
					if(!pointObj || pointObj.x == '' || pointObj.x == '0') {
						return;
					}
					this.lineMoveCarPoint(pointObj);
		          	var res='';
		        	var len=params.length;
		        	for(var i=0;i<len;i++){
		        		res=res+params[i].marker+params[i].seriesName+':'+params[i].data+'</br>'
		        	}
		        	return res;
		
		        }.bind(this)
			},
			grid: {
				left: '48px',
				right: '12px',
				top:'20%',
				bottom:'18%'
			},
			toolbox: {
		        feature: {
		            dataView: {show: false, readOnly: false},
		            restore: {show: false},
		            saveAsImage: {show: false}
		        }
	    	},
			legend: {
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: [],		
			},
			yAxis: [this.yAxiWeight],
			
		    dataZoom: [{
	            
	            realtime: true
	        }, {
	            type: 'inside',
	            realtime: true,
	        }],
			series: [
//				{name: '重量',type: 'line',data: []}
			]
		};
	}
	initChartyAxi(){
		this.yAxiWeight={
			show:true,
			name: '速度',
			type: 'value',
	   	 	position: 'left',
	   	 	min:undefined,
	   	 	max:undefined,
			offset: undefined,
			splitLine:{
	            lineStyle:{
					color:'#eee'
				}
	        },
	   	 	splitNumber:4,
	   	 	axisLine: {
	            lineStyle: {
	                color: 'gray'
	            }
	    	},
			axisLabel: {
				formatter: '{value}'
			}
		}
		this.yAxiSignal={
			show:false,
			name: '信号',
			splitLine:{
	            show:false
	        },
			type: 'value',
			position: 'right',
			min:undefined,
	   	 	max:undefined,
			offset: undefined,
			axisLine: {
	            lineStyle: {
	                color: '#5c427c'
	            }
	    	},
			axisLabel: {
				formatter: '{value}'
			}
		}
		this.yAxiSpeed={
			show:false,
			name: '速度 KM/H',
			splitLine:{
	           show:false
	        },
			type: 'value',
			min:undefined,
	   	 	max:undefined,
			offset: 60,
			position: 'right',
			axisLine: {
	            lineStyle: {
	                color: '#5793f3'
	            }
	    	},
			axisLabel: {
				formatter: '{value}'
			}
		}
	}
	
	closeChartEvent(){
		this.timePlayer=false;
		
	}
	
}